package server

import (
	"distributed/message"
	"fmt"
)

var taskReadyChan chan chan message.ReptileReq

func Scheduler() {
	go func() {
		taskReadyChan = make(chan chan message.ReptileReq)
		var taskList []message.ReptileReq
		var readyList []chan message.ReptileReq
		for {
			select {
			case task := <-taskChan:
				taskList = append(taskList, task)
			case ready := <-taskReadyChan:
				readyList = append(readyList, ready)
			}
			if len(taskList) != 0 && len(readyList) != 0 {
				fmt.Printf("[ Scheduler ] readyList: %v\ttaskLen: %v\n", len(readyList), len(taskList))
				ready := readyList[0]
				task := taskList[0]
				ready <- task
				readyList = readyList[1:]
				taskList = taskList[1:]

				taskLen := len(taskList)
				if taskLen > 10 {
					fmt.Printf("[ taskList ] len: %v\n", taskLen)
					point := [9]int{}
					for i := 0; i < 10; i++ {
						point[0] = 0
						point[8] = taskLen - 1
						point[4] = (point[0] + point[8]) / 2

						point[2] = (point[0] + point[4]) / 2
						point[6] = (point[4] + point[8]) / 2

						point[1] = (point[0] + point[2]) / 2
						point[3] = (point[2] + point[4]) / 2

						point[5] = (point[4] + point[6]) / 2
						point[7] = (point[6] + point[8]) / 2
					}
					fmt.Printf("[ taskList ] point：%v\n", point)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[0], taskList[point[0]].URL, taskList[point[0]].Limit, taskList[point[0]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[1], taskList[point[1]].URL, taskList[point[1]].Limit, taskList[point[1]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[2], taskList[point[2]].URL, taskList[point[2]].Limit, taskList[point[2]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[3], taskList[point[3]].URL, taskList[point[3]].Limit, taskList[point[3]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[4], taskList[point[4]].URL, taskList[point[4]].Limit, taskList[point[4]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[5], taskList[point[5]].URL, taskList[point[5]].Limit, taskList[point[5]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[6], taskList[point[6]].URL, taskList[point[6]].Limit, taskList[point[6]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[7], taskList[point[7]].URL, taskList[point[7]].Limit, taskList[point[7]].Offset)
					fmt.Printf("[ taskList ] index: %v\turl: %v\tlimit: %v\toffset: %v\n", point[8], taskList[point[8]].URL, taskList[point[8]].Limit, taskList[point[8]].Offset)
				}
			}

		}
	}()
}
